/*
TODO:
Write data to file
Allow port selection on startup
Make GUI a bit better
*/

package
{
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.net.Socket;
	import flash.text.TextField;
	import flash.utils.Endian;
	
	public class SerialTester extends Sprite
	{
		private var _connector:Socket=new Socket();
		private var _textField:TextField=new TextField();
		
		private var _time:Vector.<uint>=new Vector.<uint>(BUFFER);
		private var _data:Vector.<uint>=new Vector.<uint>(BUFFER);
		private var _p:Number=0;
		
		private const BUFFER:int=10240;
		
		public function SerialTester()
		{
			stage.scaleMode=StageScaleMode.EXACT_FIT;
			_connector.connect("127.0.0.1",5333);
			_connector.addEventListener("socketData",onSocketData);
			this.addEventListener(Event.ENTER_FRAME,onEnterFrame);
			_connector.writeByte(0);
			_connector.endian=Endian.LITTLE_ENDIAN;
		}
		
		public function onEnterFrame(event:Event):void{
			var dx:Number=stage.stageWidth/BUFFER;
			var dy:Number=stage.stageHeight/1024;
									
			graphics.clear();
			graphics.moveTo(0,stage.stageHeight-(_data[_p%BUFFER]*dy));
			graphics.lineStyle(0.5,0x8833CCFF);
			
			for(var i:Number=0; i<BUFFER; i+=10){
				graphics.lineTo(i*dx,stage.stageHeight-(_data[(_p+i)%BUFFER]*dy));
			}
			
		}
		
		public function onSocketData(event:Event):void{
			while(_connector.bytesAvailable>=6){
				_time[_p]=_connector.readUnsignedInt();
				_data[_p++]=_connector.readUnsignedShort();
				_p%=BUFFER;
				_connector.writeByte(0xF0);
			}
		}
	}
}